package org.example.demo9;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 案例主要逻辑在这里
 * @author Gong.Yang
 */
@Component
public class RepositoryRegister implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AssignableTypeFilter(DataEntity.class));

        Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents("org.example.demo9.scanPackage");
        for (BeanDefinition beanDefinition : candidateComponents) {
            String beanClassName = beanDefinition.getBeanClassName();
            AbstractBeanDefinition repositoryDefinition = BeanDefinitionBuilder.genericBeanDefinition(BaseRepository.class)
                    .addConstructorArgValue("my name is xxoo")
                    .addConstructorArgValue(beanClassName)
                    .addConstructorArgValue(Application.class)
                    .getBeanDefinition();
            int beginIndex = beanClassName.lastIndexOf(".");
            String beanName = beanClassName.substring(beginIndex, beginIndex + 1).toLowerCase() + beanClassName.substring(beginIndex + 1)+"BaseRepository";
            registry.registerBeanDefinition(beanName,repositoryDefinition);
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
